# -*- coding: utf-8 -*-
import base64
import hashlib
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://api.1yigou.com.cn:8881/merchant-trade-api/command'
# 零点是接durota
APP_CONF = {
    '95272028': {
        'API_KEY': '594b418605b05e1c93db48c15b632b9b',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 210110,210112,210101，220002，220001，210113
# 跳转银联在线预下单
def _get_pay_type(service):
    return '210113'


def gen_sign_str(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        # if parameter[k] != '' and parameter[k] != None:
        if parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    return s[0:len(s) - 1]


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['Signature']
    params.pop('Signature')
    params.pop('SignMethod')
    calculated_sign = generate_sign(gen_sign_str(params) + key)
    if sign != calculated_sign:
        _LOGGER.info("zeropay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('TxCode', _get_pay_type(service)),
        ('MerNo', app_id),
        ('ProductId', '0615'),
        ('TxSN', str(pay.id)),
        ('Amount', str(int(pay_amount * 100))),
        ('PdtName', 'charge'),
        ('NotifyUrl', '{}/pay/api/{}/zeropay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ReqTime', time.strftime("%Y%m%d%H%M%S")),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['Signature'] = generate_sign(s + api_key)
    parameter_dict['SignMethod'] = 'MD5'
    _LOGGER.info("zeropay create  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zeropay create rsp data: %s %s", response.status_code, response.text)
    url = _get_str(response.text, '&PayUrl=', '&')
    url = urllib.unquote(url)
    url = base64.b64decode(url)
    _LOGGER.info("zeropay create rsp url: %s", url)
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("zeropay notify data: %s", data)
    _LOGGER.info("zeropay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['TxSN']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('zeropay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['Status'])
    trade_no = data['PlatTxSN']
    total_fee = float(data['Amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 交易状态
    # 0:未处理
    # 1:成功
    # 2:处理中
    # 3:失败
    if trade_status == '1':
        _LOGGER.info('zeropay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('TxCode', '210101'),
        ('MerNo', app_id),
        ('TxSN', str(pay_id)),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['Signature'] = generate_sign(s + api_key)
    parameter_dict['SignMethod'] = 'MD5'
    _LOGGER.info("zeropay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("zeropay query rsp data: %s %s", response.status_code, response.text)
    if response.status_code == 200:
        trade_status = _get_str(response.text, 'Status=', '&')
        trade_no = _get_str(response.text, 'PlatTxSN=', '&')
        total_fee = float(_get_str(response.text, 'Amount=', '&')) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 交易状态
        # 0:未处理
        # 1:成功
        # 2:处理中
        # 3:失败
        if trade_status == '1':
            _LOGGER.info('zeropay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('zeropay data error, status_code: %s', response.status_code)
